/*
 * Get rolesmaps by server and filter routes by roles
 */

import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * My Function: Merge routes with rolesmap
 * @param routes asyncRoutes
 * @param maps rolesmap
 */
function mergeRolesMap (routes, maps) {
  const res = routes.map(route => {
    if (maps[route.name]) {
      route.meta.roles = maps[route.name]
    }
    if (route.children) {
      mergeRolesMap(route.children, maps)
    }
    return route
  })
  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes ({ commit }, { roles, maps }) {
    return new Promise(resolve => {
      // Get rolesmaps by server and filter routes by roles
      const mergeRoutes = mergeRolesMap(asyncRoutes, maps)
      const accessedRoutes = filterAsyncRoutes(mergeRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
